require('dotenv').config()
const express = require('express')
const http = require('http')
const cors = require('cors')
const { expressjwt } = require('express-jwt')
const { Server } = require('socket.io');
const setupSockets = require('./core/socket/index.js')

const app = express();
const server = http.createServer(app);

const io = new Server(server, {
    cors: {
        origin: "*"
    }
});

setupSockets(io);

app.use('/upload', express.static(__dirname + '/upload')) // 设置静态资源目录
app.use(express.urlencoded({ extended: false })) // 解析请求体
app.use(express.json()) // 解析请求体
app.use(cors()) // 允许跨域请求
app.use(expressjwt({
    secret: process.env.SECRET_KEY,
    algorithms: ['HS256'],
}).unless({
    path: [
        '/user/login',
        '/user/register',
        '/user/verify'
    ],
}))

// 引入路由
const usersRouter = require('./router/users.js')
app.use('/user', usersRouter)
const friendshipRouter = require('./router/friendship.js')
app.use('/friend', friendshipRouter)
const groupchatRouter = require('./router/groupchat.js')
app.use('/groupchat', groupchatRouter)
const uploadRouter = require('./router/upload.js')
app.use('/upload', uploadRouter)
const chatRouter = require('./router/chat.js')
app.use('/chat', chatRouter)

// 监听端口
const port = process.env.PORT

// 启动服务
server.listen(port, () => {
    console.log(`✅ Express 服务启动成功： http://localhost:${port}`);
})